package com.cyzy.server.controller.user;

import com.cyzy.common.constant.JwtClaimsConstant;
import com.cyzy.common.properties.JwtProperties;
import com.cyzy.common.result.Result;
import com.cyzy.common.utils.JwtUtil;
import com.cyzy.pojo.dto.MyDTO;
import com.cyzy.pojo.dto.UserLoginDTO;
import com.cyzy.pojo.entity.StudentAuth;
import com.cyzy.pojo.entity.User;
import com.cyzy.pojo.vo.HuntCardVO;
import com.cyzy.pojo.vo.RecruitCardVO;
import com.cyzy.pojo.vo.UserLoginVO;
import com.cyzy.server.service.HuntCardService;
import com.cyzy.server.service.RecruitCardService;
import com.cyzy.server.service.StarService;
import com.cyzy.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private HuntCardService huntCardService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    RecruitCardService recruitCardService;
    @Autowired
    StarService starService;

    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("微信用户登录：{}", userLoginDTO.getCode());

        //微信登陆
        User user = userService.wxLogin(userLoginDTO);

        //为微信用户生成jwt令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder().
                id(user.getId()).
                openid(user.getOpenid()).
                token(token).
                build();

        return Result.success(userLoginVO);
    }

    /**
     * 个人主页
     * @Param userId
     * @return
     */
    @GetMapping("My")
    @ResponseBody
    public Result<MyDTO> my(@RequestParam(value = "id") Integer userId){

        MyDTO myDTO = userService.getMyInfo(userId);
        if (myDTO==null){
            log.error("用户拉取主页数据失败:{}", String.valueOf(userId));
            return Result.error("请求失败，无数据！");
        }


        return Result.success(myDTO);
    }

    /**
     * 我的招募贴
     */
    @GetMapping("myRecruit")
    @ResponseBody
    public Result myRecruit(@RequestParam(value = "id") Integer userId){


        List<RecruitCardVO> recruitCardVOS = recruitCardService.selectRecruitCardListByUserId(userId);

        if (recruitCardVOS==null){
            log.error("用户拉取本人发布招募贴列表失败:{}", String.valueOf(userId));
            return Result.error("请求失败，无数据！");
        }


        return Result.success(recruitCardVOS);
    }

    /**
     * 我的求职贴
     */
    @GetMapping("myHunt")
    @ResponseBody
    public Result myHunt(@RequestParam(value = "id") Integer userId){


        List<HuntCardVO> huntCardVOS = huntCardService.selectHuntCardListByUserId(userId);

        if (huntCardVOS==null){
            log.error("用户拉取本人发布求职贴列表失败:{}", String.valueOf(userId));
            return Result.error("请求失败，无数据！");
        }


        return Result.success(huntCardVOS);
    }

    /**
     * 我的收藏
     */
    @GetMapping("/myCollection")
    public Result collectionList(@RequestParam(value = "id") Integer id,
                                 @RequestParam(value = "type") String type) {
        if (type.equals("hunt")) {
            List<HuntCardVO> huntCardVOS = starService.selectHuntStars(id);
            if(huntCardVOS!=null){
                return Result.success(huntCardVOS);
            }else {
                return Result.error("请求失败，无数据！");
            }

        } else if (type.equals("recruit")) {
            List<RecruitCardVO> recruitCardVOS = starService.selectRecruitStars(id);
            if(recruitCardVOS!=null){
                return Result.success(recruitCardVOS);
            } else {
                return Result.error("请求失败，无数据！");
            }
        }

        return Result.error("请求失败，无数据！");
    }

    /**
     * 个人信息设置
     */
    @PostMapping("setProfile")
    @ResponseBody
    public Result setProfile(@RequestParam(value = "id") Integer userId, @RequestBody Map map){
        userService.setProfile(userId, map);
        return Result.success("更改成功");
    }

    /**
     * 设置个人头像
     */
    @PostMapping("setAvatar")
    @ResponseBody
    public Result setAvatar(@RequestParam(value = "id") Integer id,
                            @RequestParam(value = "path") String path) {
        userService.setAvatar(path, id);
        return Result.success("设置成功");
    }

    /**
     * 学生认证接口
     */
    @PostMapping("studentCertification")
    @ResponseBody
    public Result studentCertification(@RequestBody StudentAuth studentAuth){
        String auth = userService.studentAuth(studentAuth);

        if (studentAuth == null){
            return Result.error("信息为空");
        }

        if (auth != null){
            return Result.error(auth);
        }


        return Result.success("学生验证成功！");
    }




    /**
     * 返回cookie接口
     */
    @GetMapping("getCookie")
    @ResponseBody
    public Result getCookie() throws Exception{
        String cookie = getCookies();
        return Result.success(cookie);

    }


    public static String getCookies() throws Exception {
        // 目标网站的URL
        String url = "http://jwxt.gdufe.edu.cn/jsxsd/xsxk/xklc_list?Ves632DSdyV=NEW_XSD_PYGL";

        //存储cookie
        String cookie = null;

        // 创建URL对象
        URL obj = new URL(url);

        // 打开URL连接
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 发送GET请求
        con.setRequestMethod("GET");

        // 获取响应代码
        int responseCode = con.getResponseCode();

        // 读取响应内容
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();


        // 获取响应中的Cookie
        Map<String, List<String>> headerFields = con.getHeaderFields();
        List<String> cookiesHeader = headerFields.get("Set-Cookie");

        // 如果有Cookie，打印Cookie
        if (cookiesHeader != null) {
            for (String cookies : cookiesHeader) {
                System.out.println(cookies.split(";\\s*")[0]);
                cookie = cookies.split(";\\s*")[0];
            }
        } else {
            System.out.println("No cookies in the response.");
        }


        return cookie;

    }

}
